<?php
/**
 * 用户管理
 */
class MemberApp extends CommonApp {
   
    
    //oauth登录
    public function oauthAct(){
        Oauth2::getInstance()->login(My::arr2var($_GET,'type'),My::arr2var($_GET,'url'));
    }
    
    
    //oauth登录域名不匹配
    public function oauth_errorAct(){
        $domain = My::arr2var($_GET,'domain');
        $this->assign('domain',$domain);
        //display
        $this->display();
    }
     
    
    //oauth回调
    public function callbackAct(){
        $host = My::arr2var($_GET,'host');
        if($host and $host!=$_SERVER['HTTP_HOST'])
            redirect("http://".$host.$_SERVER["REQUEST_URI"]);
        $type = My::arr2var($_GET,'type');
        $appname = My::arr2var($_GET,'appname');
        if(!in_array(strtoupper($type), Oauth2::getInstance()->getOauthType()))
            $this->ajaxReturn(404,'未知的第三方登录类型！');
        $result = Oauth2::getInstance()->handleCallback(My::arr2var($_GET,'type'),My::arr2var($_GET,'code'));
        $oauth_type=C('oauth_type');
        if(!My::arr2var($result,'openid'))
            $this->ajaxReturn(404,'获取'.$oauth_type[$type].'用户信息失败！');
        $_SESSION[$type.'OauthCache'] = $result;
        //后台的第三方登录
        if($appname=='admin'){
            self::redirect2(Router::encodeUrl("index.php?app=admin/public&act=bind&type={$type}"));
        }
        //前台第三方登录
        else{
            self::redirect2(Router::encodeUrl("index.php?app=member&act=bind&type={$type}"));
        }
    }
    
    
    /**
     * (parent)跳转至指定的路径
     * @param string $url 路径
     */
    function redirect2($url)
    {
        $html = "<script>try{if(parent.location.href!=window.location.href || window.opener.location.href == parent.location.href){parent.location.href='{$url}';}else{window.opener.location.href='{$url}';window.opener=null;window.open('','_self');window.close();}}catch(e){window.location.href='{$url}';}</script>";
        exit ($html);
    }
    
    
    //第三方登录用户绑定
    public function bindAct(){
        $login_type = C('oauth_type');
        if($_POST){
            
        }else{
            $type = My::arr2var($_GET,'type');
            if(!in_array(strtoupper($type), Oauth2::getInstance()->getOauthType()))
                $this->ajaxReturn(404,'未知的第三方登录类型！');
            $openid = My::arr2var($_SESSION,$type.'OauthCache.openid');
            $nickname = My::arr2var($_SESSION,$type.'OauthCache.nickname');
            if(!$openid)
                $this->ajaxReturn(404,'获取'.$login_type[$type].'用户信息失败！');
            $member = DB('member')->where("openid_{$type}='{$openid}'")->find();
            //已经绑定了一个帐号
            if($member){
                M('admin.helper')->setLoginSession($member['id'], $nickname);
                if(My::arr2var($_COOKIE,'history_url'))
                    redirect($_COOKIE['history_url']);
                else
                    redirect(__PROJECT__);
            }
            //未绑定帐号
            else{
                $this->assign('oauthNickname',$nickname);
            }
        }
        //display
        $this->display();
    }
    
    
    //绑定用户
    private function bindMember($member,$type){
        $logged = My::is_id(My::arr2var($_SESSION,'member.id')) ? true : false;//已登录
        $login_type = C('oauth_type');
        $openid = My::arr2var($_SESSION,$type.'OauthCache.openid');
        $nickname = My::arr2var($_SESSION,$type.'OauthCache.nickname');
        //过滤掉昵称中的非UTF-8的字符
        $nickname = M('admin.helper')->filter_utf8_char($nickname);
        if(My::arr2var($member,'openid_'.$type)!=''){
            if($logged)
                redirect(Router::encodeUrl('index.php?app=member&act=bindsns&code=03'));
            else
                $this->ajaxReturn(300,'该帐号已经绑定了一个'.$login_type[$type].'用户!');
        }
        $params = My::decodeJson($member['params']);
        $params['nickname'][$type] = $nickname;
        $data = array();
        $data['openid_'.$type] = My::arr2var($_SESSION,$type.'OauthCache.openid');
        $data['params'] = $params;
        if(!$member['headimage'])
            $data['headimage'] = My::arr2var($_SESSION,$type.'OauthCache.headimage');
        $ok = DB('member')->where("id={$member['id']}")->clear()->save($data);
        if($ok){
            unset($_SESSION[$type.'OauthCache']);
            if($logged)
                redirect(Router::encodeUrl('index.php?app=member&act=bindsns&code=01'));
            else{
                M('admin.helper')->setLoginSession($member['id'], $nickname);
                $this->ajaxReturn(200,'绑定帐号成功');
            }
        }else{
            if($logged)
                redirect(Router::encodeUrl('index.php?app=member&act=bindsns&code=02'));
            else{
                $this->ajaxReturn(300,'绑定帐号失败，db错误！');
            }
        }
    }
    
    /**
     * 用户管理 -> 修改个人信息
     */
    public function infoAct(){
        //判断是否已登录,如未登录则跳转到登录页面
    	$this->checkLogin();
        $member = My::arr2var($_SESSION,'member');
        if($_POST){
            $tel = My::arr2var($_POST,'tel');
            $email = My::arr2var($_POST,'email');
            $password_old = My::arr2var($_POST,'password_old');
            $password_new = My::arr2var($_POST,'password_new');
            $password_new2 = My::arr2var($_POST,'password_new2');
            //是否要修改密码
            if($password_old!=''){
                $password_old = MD5(MD5($password_old));
                if(!DB('member')->where("username='{$member['username']}' AND password='{$password_old}'")->find()){
                    $this->ajaxReturn(300,'旧密码不正确!');
                }elseif(strlen($password_new)<7){
                    $this->ajaxReturn(300,'新密码不能小于7位!');
                }elseif($password_new!=$password_new2){
                    $this->ajaxReturn(300,'两次新密码不一致!');
                }
                $data['password'] = MD5(MD5($password_new));
            }
            if(!My::is_email($email) and $email!=''){
                $this->ajaxReturn(300,'邮箱地址有误!');
            }elseif(strlen($email)>30){
	           $this->ajaxReturn(300,'邮箱地址不能超过30个字符!');
            }elseif(DB('member')->where("(email='{$email}' OR username='{$email}') AND id<> {$member['id']}")->cache()->count()>0)
    		    $this->ajaxReturn(300,'该邮箱已存在,请填写别的邮箱!');
            else{
                $data['email'] = $email;
            }
            if(!My::is_tel($tel) and $tel!=''){
                $this->ajaxReturn(300,'电话号码有误!');
            }elseif(strlen($tel)>20){
	           $this->ajaxReturn(300,'电话号码不能超过20个字符!');
            }else{
                $data['tel'] = $tel;
            }
            $ok = DB('member')->where("username='{$member['username']}'")->clear()->save($data);
            if($ok>=0){
                $this->ajaxReturn(200,'修改成功!');
            }else{
                $this->ajaxReturn(300,'修改失败!');
            }
        }else{
            //用户信息
            $result = DB('member')->where("username='{$member['username']}'")->find();
            $this->assign('result',$result);
            //display
            $this->display();
        }
    }

}